/**
 * 淡入动画指令
 * 使用 IntersectionObserver 监听元素进入视口
 * 只触发一次动画效果
 */

const animateOnScroll = (el, binding) => {
    const direction = binding.arg || 'up' // 默认从下往上
    const distance = binding.value?.distance || 30 // 移动距离
    const duration = binding.value?.duration || 600 // 动画时长
    const delay = binding.value?.delay || 0 // 延迟时间

    // 设置初始状态 - 完全透明
    el.style.opacity = '0'
    el.style.visibility = 'visible'
    // 使用 cubic-bezier 实现更灵动的效果
    el.style.transition = `opacity ${duration}ms cubic-bezier(0.34, 1.56, 0.64, 1) ${delay}ms, transform ${duration}ms cubic-bezier(0.34, 1.56, 0.64, 1) ${delay}ms`

    // 根据方向设置初始位置
    const transforms = {
        up: `translateY(${distance}px)`,
        down: `translateY(-${distance}px)`,
        left: `translateX(${distance}px)`,
        right: `translateX(-${distance}px)`
    }

    el.style.transform = transforms[direction] || transforms.up

    // 创建 IntersectionObserver
    const observer = new IntersectionObserver(
        (entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    // 使用 requestAnimationFrame 确保动画流畅
                    requestAnimationFrame(() => {
                        // 元素进入视口，触发动画
                        el.style.opacity = '1'
                        el.style.transform = 'translate(0, 0)'
                    })

                    // 动画完成后断开观察，确保只触发一次
                    setTimeout(() => {
                        observer.unobserve(el)
                        observer.disconnect()
                    }, duration + delay + 100)
                }
            })
        },
        {
            threshold: 0.15, // 元素15%可见时触发
            rootMargin: '0px 0px -30px 0px' // 提前触发动画
        }
    )

    // 开始观察
    observer.observe(el)

    // 保存 observer 到元素上，便于卸载时清理
    el._fadeObserver = observer
}

// 创建指令对象
const createFadeDirective = (direction) => ({
    mounted(el, binding) {
        animateOnScroll(el, { ...binding, arg: direction })
    },
    unmounted(el) {
        // 清理 observer
        if (el._fadeObserver) {
            el._fadeObserver.disconnect()
            delete el._fadeObserver
        }
    }
})

// 导出四个方向的指令
export const fadeUp = createFadeDirective('up')
export const fadeDown = createFadeDirective('down')
export const fadeLeft = createFadeDirective('left')
export const fadeRight = createFadeDirective('right')

// 默认导出所有指令
export default {
    fadeUp,
    fadeDown,
    fadeLeft,
    fadeRight
}
